package com.java.socket.udp.mulitclient.whileloop.sender;

import java.io.IOException;
import java.net.*;
import java.nio.charset.Charset;

/**
 * 多客户端udp socket通信客户端程序
 *
 * @author xzmeasy
 * @version 1.0
 * @since 星期一 十二月,2018
 */
@SuppressWarnings("Duplicates")
public class DatagramSender {

    public static void main(String[] args) {
        try {
            // 创建DatagramSocket
            DatagramSocket sendSocket = new DatagramSocket();
            // 创建要发送给服务端的数据包
            byte[] sendData = "发送方发送的数据".getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length);
            sendPacket.setAddress(InetAddress.getByName("localhost"));
            sendPacket.setPort(8888);
            // 发送数据
            sendSocket.send(sendPacket);
            // 关闭DatagramSocket
//            sendSocket.close();


            // 接收接收方的反馈数据，此处端口号不能与上面的一样，因为上面的端口已经被占用
            DatagramSocket receiveSocket = new DatagramSocket(8889);
            // 创建接收数据的数据包
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            // 接收数据
            receiveSocket.receive(receivePacket);
            System.out.println("接收方反馈的数据: " + new String(receivePacket.getData(), Charset.forName("utf-8")) + ", 数据来自" + receivePacket.getSocketAddress().toString());
            // 关闭资源
//            receiveSocket.close();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
